package com.duo.utils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: Xrx
 * @Description:
 * @CreateTime: 2023/7/10 17:17
 */
public class OrderUtils {

    private static LocalDate currentDate = LocalDate.now();

    private static final AtomicInteger counter = new AtomicInteger(0);

    private static final String DATE_FORMAT = "yyyyMMddHHmmssSSS";

    private static final int RANDOM_NUMBER_BOUND = 1000;

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    private static int sequence = 0;

    private static final Random random = new Random();

    /**
     * 生成取餐码
     * @return
     */
    public static Integer getDeliverCode () {
        LocalDate today = LocalDate.now();
        if (!today.equals(currentDate)) {
            currentDate = today;
            counter.set(0);
        }
        return counter.incrementAndGet();
    }

    /**
     * 生成订单号
     * @return
     */
    public static synchronized String generateOrderNumber() {
        StringBuilder orderNumberBuilder = new StringBuilder();
        // 生成时间戳部分
        orderNumberBuilder.append(dateFormat.format(new Date()));
        // 生成序列号部分
        orderNumberBuilder.append(generateSequence());
        return orderNumberBuilder.toString();
    }

    private static String generateSequence() {
        if (sequence >= RANDOM_NUMBER_BOUND) {
            sequence = 0;
        }
        return String.format("%03d", sequence++);
    }

}
